package com.aua.book.android.xml;

import android.util.FloatMath;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class GestureListener implements View.OnTouchListener {

  GestureListener(AndroidBookActivity app) {
    this.app = app;
    gestureDetector = new GestureDetector(new MyGestureDetector(this.app));
  }

  private final int NONE = 0;
  private final int ZOOM = 1;
  private int mode = NONE;
  private int oldDist = 1;
  AndroidBookActivity app;
  final GestureDetector gestureDetector;

  public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_POINTER_DOWN:
      oldDist = spacing(event);
      mode = ZOOM;
      break;
    case MotionEvent.ACTION_POINTER_UP:
      mode = NONE;
      break;

    case MotionEvent.ACTION_MOVE:

      if (mode == ZOOM) {
        float newDist = spacing(event);

        float scale = newDist / oldDist;

        if (scale > 1
            && ZoomHelper.getZoomP(app, app.getTextView()) < Integer.parseInt(app
                .getString(R.string.maxZoomPercent)))
          app.setCurrentSize( ZoomHelper.zoomIn(app, Float.parseFloat(app.getString(R.string.touchZoom)),
              app.getTextView(), app.getZoomTextView()));

        else if (scale < 1
            && ZoomHelper.getZoomP(app, app.getTextView()) >= Integer.parseInt(app
                .getString(R.string.minZoomPercent)))
          app.setCurrentSize( ZoomHelper.zoomOut(app, Float.parseFloat(app.getString(R.string.touchZoom)),
              app.getTextView(), app.getZoomTextView()));

      }
      break;
    }
   
    return gestureDetector.onTouchEvent(event);

  }

  private int spacing(MotionEvent event) {
    int x = (int) event.getX(0) - (int) event.getX(1);
    int y = (int) event.getY(0) - (int) event.getY(1);
    return (int) FloatMath.sqrt(x * x + y * y);
  }
}
